﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Mechanical;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.LIB;
using YArchitech.ProgressBar;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	internal class DikuTestCommandTestA : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Document document = commandData.Application.ActiveUIDocument.Document;
			Level genLevel = document.ActiveView.GenLevel;
			UIApplication application = commandData.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(1);
			if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			Category lineCategory = null;
			GroundStorehouseNozzle.CreateLineStyle(document, ref lineCategory);
			List<Element> list = new List<Element>();
			FormlaySprinklerBasement formlaySprinklerBasement = new FormlaySprinklerBasement(document);
			if (formlaySprinklerBasement.ShowDialog() != DialogResult.OK)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			HideWarningAndErroringKit @object = new HideWarningAndErroringKit(new List<string>
			{
				"C"
			}, HideWarningAndErroringKit.HideKitEnum.HideWarning);
			commandData.Application.Application.FailuresProcessing += @object.OnFailuresProcessing;
			IList<Space> list2 = new LayGroundStorehouseNozzle(commandData, formlaySprinklerBasement.layParameter).CreateSpaceByLinkDoc(application);
			Element element = null;
			try
			{
				XYZ locPoint = application.ActiveUIDocument.Selection.PickPoint("请选取房间内一点！");
				element = GroundStorehouseNozzle.GetNearRoom(document, locPoint);
			}
			catch (Exception)
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			if (element == null)
			{
				YJKMessageBox.Show("选中房间没有包含车库关键字或者选择点不在房间范围内，请重新选择！");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			list.Add(element);
			List<Curve> list3 = new List<Curve>();
			List<List<Curve>> listList = GroundStorehouseNozzle.GetListList(list, ref list3);
			List<FilledRegion> list4 = new List<FilledRegion>();
			FilledRegion filledRegion = GroundStorehouseNozzle.CreateRegion(application, list3, false);
			if (filledRegion != null)
			{
				list4.Add(filledRegion);
			}
			if (listList.Count > 0)
			{
				for (int i = 0; i < listList.Count - 1; i++)
				{
					FilledRegion filledRegion2 = GroundStorehouseNozzle.CreateRegion(application, listList[i], true);
					if (filledRegion2 != null)
					{
						list4.Add(filledRegion2);
					}
				}
			}
			if (MessageBox.Show("是否布置在该区域！", "确认", MessageBoxButtons.YesNo) == DialogResult.No)
			{
				Transaction transaction = new Transaction(document, "del");
				try
				{
					transaction.Start();
					foreach (FilledRegion filledRegion3 in list4)
					{
						document.Delete(filledRegion3.Id);
					}
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
				}
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			if (GroundStorehouseNozzle.IsNozzleInRoom(list[0], document))
			{
				YJKMessageBox.Show("房间内已存在喷头，请删除后重新布置！");
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			ProgressBarForm progressBarForm = new ProgressBarForm(8, ProgressBarStyle.Blocks, true);
			progressBarForm.Text = "地库喷头布置";
			progressBarForm.ShowInTaskbar = false;
			progressBarForm.Show(this._wndRevit);
			progressBarForm.Text = "获取空间中...";
			progressBarForm.RefreshProgressBar();
			TextNoteOptions textNoteOptions = new TextNoteOptions();
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
			filteredElementCollector.OfClass(typeof(TextNoteType));
			FilteredElementIterator elementIterator = filteredElementCollector.GetElementIterator();
			elementIterator.Reset();
			TextNoteType textNoteType = elementIterator.Current as TextNoteType;
			textNoteOptions.TypeId = textNoteType.Id;
			if (new SpaceFamilyDataReader().GetFamilySymbolById(1, "Sprinkler", "DN15", document, BuiltInCategory.OST_Sprinklers) == null)
			{
				progressBarForm.Close();
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			Transaction transaction2 = new Transaction(document, "c");
			try
			{
				transaction2.Start();
				progressBarForm.Text = "合并闭合区域...";
				progressBarForm.RefreshProgressBar();
				GroundStorehouseNozzle groundStorehouseNozzle = new GroundStorehouseNozzle();
				List<Curve> roomCurves = list3;
				new List<List<Curve>>();
				List<List<Curve>> list5 = listList;
				groundStorehouseNozzle.GetLstLstCurve(document, lineCategory, list, ref list5);
				List<Curve> removeLittleLine = GroundStorehouseNozzle.GetRemoveLittleLine(document, list5.Last<List<Curve>>(), 1200.0);
				if (removeLittleLine != null)
				{
					list5.Remove(list5.Last<List<Curve>>());
					list5.Add(removeLittleLine);
				}
				List<List<Curve>> list6 = new List<List<Curve>>();
				foreach (List<Curve> list7 in list5)
				{
					List<Curve> list8 = new List<Curve>();
					foreach (Curve curve in list7)
					{
						list8.Add(curve.Clone());
					}
					list6.Add(list8);
				}
				progressBarForm.Text = "正在划分区域...";
				progressBarForm.RefreshProgressBar();
				ElementFilter elementFilter = new ElementCategoryFilter(BuiltInCategory.OST_Columns);
				ElementCategoryFilter elementCategoryFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns);
				LogicalOrFilter elementFilter2 = new LogicalOrFilter(elementFilter, elementCategoryFilter);
				ElementCategoryFilter elementFilter3 = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming);
				ElementClassFilter elementFilter4 = new ElementClassFilter(typeof(Wall));
				GroundStorehouseNozzle.GetElementsByRoomArea(document, list.First<Element>(), elementFilter3);
				IList<Element> inSpaceColumn = GroundStorehouseNozzle.GetInSpaceColumn(GroundStorehouseNozzle.GetElementsByRoomArea(document, list.First<Element>(), elementFilter2), roomCurves);
				GroundStorehouseNozzle.GetElementsByRoomArea(document, list.First<Element>(), elementFilter4);
				if (inSpaceColumn != null && inSpaceColumn.Count > 0)
				{
					groundStorehouseNozzle.SetRoomBoundingFalse(inSpaceColumn.ToList<Element>(), document);
				}
				List<Curve> lst = groundStorehouseNozzle.RoomAndGridSegment(document, list5, list5.Last<List<Curve>>(), inSpaceColumn);
				GroundStorehouseNozzle.RemoveRepeatCurves(ref lst);
				List<List<Curve>> allCloseCurves = groundStorehouseNozzle.GetAllCloseCurves(lst);
				if (allCloseCurves.Count == 0)
				{
					YJKMessageBox.Show("没有找到合适区域!");
					transaction2.RollBack();
					progressBarForm.Close();
					return Autodesk.Revit.UI.Result.Cancelled;
				}
				progressBarForm.Close();
				List<RectStruct> lstRect = AnalysisStruct.AnalysisRectRegions(allCloseCurves);
				AnalysisStruct.SignRegion(document, lstRect, lineCategory);
				foreach (FilledRegion filledRegion4 in list4)
				{
					document.Delete(filledRegion4.Id);
				}
				foreach (Space space in list2)
				{
					document.Delete(space.Id);
				}
				transaction2.Commit();
			}
			catch (Exception ex)
			{
				progressBarForm.Close();
				transaction2.RollBack();
				YJKMessageBox.Show(ex.ToString());
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public Dictionary<Room, Transform> GetLinkAllRoom(UIApplication uiApp)
		{
			Dictionary<Room, Transform> dictionary = new Dictionary<Room, Transform>();
			Document document = uiApp.ActiveUIDocument.Document;
			FilteredElementCollector elementsOfType = YJKElementFilter.GetElementsOfType(document, typeof(Instance), BuiltInCategory.OST_RvtLinks);
			IList<string> linkFilePaths = YJKRevitTools.GetLinkFilePaths(document);
			foreach (Element element in elementsOfType)
			{
				Instance instance = element as Instance;
				if (instance != null)
				{
					Transform totalTransform = instance.GetTotalTransform();
					(document.GetElement(instance.GetTypeId()) as RevitLinkType).GetParameter(BuiltInParameter.WALL_ATTR_ROOM_BOUNDING).Set(1);
					string value = instance.Name.Substring(0, instance.Name.IndexOf(".rvt"));
					string text = "";
					foreach (string text2 in linkFilePaths)
					{
						if (text2.Contains(value))
						{
							text = text2;
						}
					}
					FilteredElementCollector filteredElementCollector = new FilteredElementCollector(uiApp.Application.OpenDocumentFile(text));
					filteredElementCollector.OfCategory(BuiltInCategory.OST_Rooms);
					foreach (Element element2 in filteredElementCollector)
					{
						Room room = element2 as Room;
						if (room.Location != null)
						{
							dictionary.Add(room, totalTransform);
						}
					}
				}
			}
			return dictionary;
		}

		private YJKWindowHandle _wndRevit;
	}
}
